#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速启动脚本
检查环境并启动应用
"""

import os
import sys
import subprocess
import json

def check_dependencies():
    """检查依赖是否安装"""
    print("🔍 检查依赖...")
    
    required_packages = [
        'flask', 'pymongo', 'flask_cors', 
        'pymysql', 'bcrypt'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"  ✅ {package}")
        except ImportError:
            print(f"  ❌ {package} (缺失)")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n⚠️  缺少依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    
    return True

def check_config():
    """检查配置文件"""
    print("\n📋 检查配置文件...")
    
    if not os.path.exists('config.json'):
        print("  ❌ config.json 文件不存在")
        return False
    
    try:
        with open('config.json', 'r') as f:
            config = json.load(f)
        
        # 检查必要的配置项
        if 'mysql' not in config:
            print("  ❌ 缺少 mysql 配置")
            return False
        
        mysql_config = config['mysql']
        required_keys = ['host', 'port', 'username', 'password', 'database', 'table']
        
        for key in required_keys:
            if key not in mysql_config:
                print(f"  ❌ 缺少 mysql.{key} 配置")
                return False
        
        print("  ✅ 配置文件检查通过")
        return True
        
    except json.JSONDecodeError:
        print("  ❌ config.json 格式错误")
        return False
    except Exception as e:
        print(f"  ❌ 配置文件检查失败: {e}")
        return False

def check_database():
    """检查数据库连接"""
    print("\n🔗 检查数据库连接...")
    
    try:
        import pymysql
        
        with open('config.json', 'r') as f:
            config = json.load(f)
        
        mysql_config = config['mysql']
        
        # 尝试连接数据库
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 检查数据库是否存在
            cursor.execute(f"SHOW DATABASES LIKE '{mysql_config['database']}'")
            result = cursor.fetchone()
            
            if not result:
                print(f"  ⚠️  数据库 '{mysql_config['database']}' 不存在")
                print("  💡 运行初始化脚本: python init_database.py")
                return False
            
            # 检查表是否存在
            cursor.execute(f"USE {mysql_config['database']}")
            cursor.execute("SHOW TABLES LIKE 'users'")
            users_table = cursor.fetchone()
            
            cursor.execute(f"SHOW TABLES LIKE '{mysql_config['table']}'")
            connections_table = cursor.fetchone()
            
            if not users_table or not connections_table:
                print("  ⚠️  数据表不完整")
                print("  💡 运行初始化脚本: python init_database.py")
                return False
        
        connection.close()
        print("  ✅ 数据库连接正常")
        return True
        
    except Exception as e:
        print(f"  ❌ 数据库连接失败: {e}")
        print("  💡 请检查MySQL服务是否启动，配置是否正确")
        return False

def main():
    """主函数"""
    print("🚀 MongoDB用户管理工具 - 启动检查")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 检查配置
    if not check_config():
        sys.exit(1)
    
    # 检查数据库
    if not check_database():
        print("\n❓ 是否要运行数据库初始化? (y/n): ", end="")
        choice = input().lower().strip()
        
        if choice in ['y', 'yes', '是']:
            print("\n🔧 运行数据库初始化...")
            try:
                subprocess.run(['python3', 'init_database.py'], check=True)
                print("✅ 数据库初始化完成")
            except subprocess.CalledProcessError:
                print("❌ 数据库初始化失败")
                sys.exit(1)
        else:
            print("❌ 数据库未初始化，无法启动应用")
            sys.exit(1)
    
    print("\n" + "=" * 50)
    print("✅ 环境检查通过，启动应用...")
    print("🌐 访问地址: http://localhost:5000")
    print("👤 默认账号: admin / admin123")
    print("=" * 50)
    
    # 启动应用
    try:
        subprocess.run(['python3', 'app.py'])
    except KeyboardInterrupt:
        print("\n👋 应用已停止")
    except Exception as e:
        print(f"\n❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()